package cn.tedu.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * 登录功能[使用预编译SQL方式,防止SQL注入攻击];
 * 1.先将预编译的SQL语句发送给数据库,让数据库理解SQL语句的执行意图,生成执行计划;
 *   SELECT nickname FROM userinfo WHERE username=? AND password=?
 * 2.设置?的值,具体数据以参数的形式传递给数据库;
 * 3.执行预编译SQL语句;
 * 4.获取查询结果集;
 */
public class JDBCLogin2 {
    public static void main(String[] args) {
        try (Connection connection = DBUtil.getConnection();){
            //接收用户名和密码
            Scanner scanner = new Scanner(System.in);
            System.out.println("用户名:");
            String username = scanner.nextLine();
            System.out.println("密码:");
            String password = scanner.nextLine();
            //定义预编译SQL语句[?代表占位符]
            String sql = "SELECT nickname FROM userinfo WHERE username=? AND password=?";
            PreparedStatement ps = connection.prepareStatement(sql);
            //设置?的值
            ps.setString(1, username);
            ps.setString(2, password);
            //执行预编译SQL
            ResultSet r = ps.executeQuery();
            if (r.next()){
                String nickname = r.getString("nickname");
                System.out.println("登录成功,欢迎您:" + nickname);
            }else {
                System.out.println("用户名或密码错误");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}










